package org.springside.examples.showcase.service.vacation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.examples.showcase.entity.Vacation;
import org.springside.examples.showcase.repository.jpa.VacationDao;

@Component
@Transactional
public class VacationService {

	private VacationDao vacationDao;
	
	public void saveVacation(Vacation entity) {
		vacationDao.save(entity);
	}
	
	public Page<Vacation> pageByUserId(Long userId, int pageNumber, int pageSize, String sortType){
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		return vacationDao.findByUser_Id(userId, pageRequest);
	}
	
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} 
//		else if ("title".equals(sortType)) {
//			sort = new Sort(Direction.ASC, "title");
//		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}
	
	
	@Autowired
	public void setVacationDao(VacationDao vacationDao) {
		this.vacationDao = vacationDao;
	}
}
